package com.simple.initializer;

import com.simple.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * WebApplicationInitializer实现web.xml的配置
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    /**
     * 初始化spring上下文以及初始化DispatcherServlet
     * @param servletContext
     * @throws ServletException
     */
    public void onStartup(ServletContext servletContext) throws ServletException {
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);
        context.refresh();

        //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("webapp", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/webapp/*");
    }
}
